package com.ruoyi.web.controller.minglvmini;

import com.minglv.mini.domain.User;
import com.minglv.mini.service.*;
import com.minglv.mini.tools.DateUtil;
import com.minglv.mini.tools.JWTUtils;
import com.minglv.mini.tools.MiniResult;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "API-首页")
@RestController
@RequestMapping("/api")
public class ApiIndexController {

    @Resource
    IUserService userService;

    @Resource
    IBannerService bannerService;
    @Resource
    ISysContentService sysContentService;

    @Resource
    IActivityService activityService;

    @Resource
    IActivityApplyService activityApplyService;

    @GetMapping("/invite/list")
    @ApiOperation("首页推荐活动列表")
    public Object getInviteList(HttpServletRequest request,@RequestParam(name = "page") Integer page,
                                @RequestParam(name = "limit",required = false) Integer limit){
        String token = request.getHeader("token");
        if (!checkToken(token)){
            Map reMap = new HashMap();
            reMap.put("code",401);
            reMap.put("msg","Token过期,或无此用户");
            return reMap;
        }
        token = token.replace(Constants.TOKEN_PREFIX, "");
        PageUtils.startPage(page,ObjectUtils.isEmpty(limit)?10:limit);
        List<Map> inviteList = activityApplyService.getInviteList(token);
        return MiniResult.success(inviteList);
    }

    @GetMapping("/index/activity")
    @ApiOperation("首页推荐活动列表")
    public Object getActivity(@RequestParam(name = "is_index") Integer is_index){
        List<Map> indexList = activityService.getIndexList(is_index);
        Map data = new HashMap();
        data.put("list", indexList);
        data.put("count", indexList.size());
        return MiniResult.success(data);
    }

    @GetMapping("/agreement/info")
    @ApiOperation("条款协议")
    public Object getAgreementInfo(HttpServletRequest request,@RequestParam(name = "type") String type){
//        String token = request.getHeader("token");
//        if (!checkToken(token)){
//            Map reMap = new HashMap();
//            reMap.put("code",401);
//            reMap.put("msg","Token过期,或无此用户");
//            return reMap;
//        }
        Map agreementInfo = sysContentService.getAgreementInfo(type);
        return MiniResult.success(agreementInfo);
    }

    @GetMapping("/index/banner")
    @ApiOperation("首页Banner")
    public Object getList(HttpServletRequest request){
//        String token = request.getHeader("token");
//        if (!checkToken(token)){
//            Map reMap = new HashMap();
//            reMap.put("code",401);
//            reMap.put("msg","Token过期,或无此用户");
//            return reMap;
//        }

        Map data = bannerService.getList();
        return MiniResult.success(data);
    }

    @GetMapping("/index/laywer")
    @ApiOperation("首页优秀律师")
    public Object getLawyer(){
        return MiniResult.success(null);
    }


    /**
     * 校验token
     * @param token
     * @return
     */
    Boolean checkToken(String token){
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        String[] s = token.split(" ");
        if (ObjectUtils.isEmpty(s) || s.length == 0) {
            return false;
        }

        token = s[1];
        Long userId = JWTUtils.getUserid(token);
        if (ObjectUtils.isEmpty(userId)) {
            return false;
        }

        User user = userService.selectUserById(userId);
        if (ObjectUtils.isEmpty(user)) {
            return false;
        }
        return true;
    }

    @PostMapping("/upload/handler")
    @ApiOperation("上传图片")
    public Object uploadHandle(MultipartFile file, String type) throws IOException {
        FileOutputStream fos = null;
        Map reMap = new HashMap();
        Map data = new HashMap();
        try {
            String path = File.separator + "upload" + File.separator + type + File.separator + DateUtil.format(DateUtil.now(), "yyyyMM");
            String fileName = DateUtil.format(DateUtil.now(), "HHmmss") + file.getOriginalFilename();
            fileName = Md5Utils.hash(fileName) + "." + FileUploadUtils.getExtension(file);
            String savapath = FileUploadUtils.getDefaultBaseDir() + path;
            File absoluteFile = FileUploadUtils.getAbsoluteFile(savapath, fileName);
            fos = new FileOutputStream(absoluteFile);
            fos.write(file.getBytes());
            data.put("title", file.getOriginalFilename());
            data.put("url", path + File.separator + fileName);
            data.put("type", type);
            data.put("size", file.getSize());
            data.put("width", 0);
            data.put("height", 0);
            reMap.put("code", 0);
            reMap.put("msg", "文件上传成功");
            reMap.put("data", data);
        } finally {
            IOUtils.close(fos);
        }

        return reMap;

    }

}
